﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

public class ConnectPannelController : MonoBehaviour
{
    // Server 输入框盖在下拉框上，只露出下接箭头。
    public InputField serverInput;
    public Dropdown serverDropdown;
    public InputField playerInput;  // 玩家名

    private List<string> recentServers;  // 最近使用的服务器，最新的在前, 总是包括 localhost:50051

    private const string KEY = "RecentServers";
    private const string SEP = ",";
    private const string DEFAULT_SERVER = "localhost:50051";

    // Start is called before the first frame update
    void Start()
    {
        serverDropdown.onValueChanged.AddListener(OnServerDropdownValueChanged);

        LoadRecentServers();
        SetServer();
    }

    private void LoadRecentServers()
    {
        string servers = PlayerPrefs.GetString(KEY);
        string[] tokens = servers.Split(SEP.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        recentServers = new List<string>(tokens);
        LimitRecentServers();
    }

    private void SaveRecentServers()
    {
        PlayerPrefs.SetString(KEY, string.Join(SEP, recentServers));
    }

    // 设置 server 下拉框和输入框
    private void SetServer()
    {
        if (recentServers.Count == 0)
        {
            recentServers.Add(DEFAULT_SERVER);
        }

        var opt = serverDropdown.options;
        opt.Clear();

        // 设置 Server 为最近值
        foreach (string s in recentServers)
        {
            var od = new Dropdown.OptionData();
            od.text = s;
            opt.Add(od);
        }
        serverDropdown.itemText.text = recentServers[0];
        serverInput.text = recentServers[0];
    }

    private void OnServerDropdownValueChanged(int index)
    {
        serverInput.text = recentServers[index];
    }

    // click "Connect" button
    public async void OnConnect()
    {
        await ConnectAsync();
    }

    private async Task ConnectAsync()
    {
        string server = serverInput.text;
        await GrpcGameClient.Instance.ConnectAsync(server);
        gameObject.SetActive(false);

        // 成功后保存
        UpdateRecentServers(server);
        SaveRecentServers();
        // SetServer();
    }

    private void UpdateRecentServers(string lastServer)
    {
        // lastServer 转为第1个
        recentServers.Remove(lastServer);
        recentServers.Insert(0, lastServer);
        LimitRecentServers();
    }

    private void LimitRecentServers()
    { 
        const int MAX_COUNT = 5;
        int count = recentServers.Count;
        if (recentServers.Count > MAX_COUNT)
        {
            recentServers.RemoveRange(MAX_COUNT, count - MAX_COUNT);  // 仅保留5个
        }

        if (!recentServers.Contains(DEFAULT_SERVER))
        {
            recentServers.Add(DEFAULT_SERVER);
        }
    }
}
